<!--核心元模型-->
<template>
  <el-row style="height: 100vh">
    <el-col :span="5" style="height: 100%; padding-left: 10px; padding-top: 20px; border-right: 1px solid #dfe6ec; display: block; overflow-y: auto">
      <customTree :ancestralId="listQuery.ancestralId" :btnTitle="'  新建目录  '" @getId="getId" :type="false" @getTree="getTree" :expandType="'1'" />
    </el-col>
    <el-col :span="19">
      <div>
        <div id="model-graph-container" ref="graphContainer" style="width: 100%; height: 100vh"></div>
      </div>
    </el-col>
    <el-drawer :title="openTableTitle" :visible.sync="nodeDrawer" :direction="direction" size="35%" :before-close="closeNodeDraw">
      <el-table :data="nodeTableInfo" style="border: 1px dashed #bbb">
        <el-table-column property="id" label="id" width="150" v-if="false"></el-table-column>
        <el-table-column property="columnName" label="英文名" width="100"></el-table-column>
        <el-table-column property="columnComment" label="中文名" width="100"></el-table-column>
        <el-table-column property="dataType" label="数据类型"></el-table-column>
        <el-table-column property="relation" label="关联字典表/字段"></el-table-column>
        <el-table-column property="valueBz" label="值域标识"></el-table-column>
      </el-table>
    </el-drawer>

    <el-drawer title="链接关系" :visible.sync="edgeDrawer" :direction="direction" size="35%" :before-close="closeNodeDraw">
      <el-table :data="edgeInfo" style="border: 1px dashed #bbb">
        <el-table-column property="id" label="id" width="150" v-if="false"></el-table-column>
        <el-table-column property="relationType" label="连接类型" width="100"></el-table-column>
        <el-table-column property="tableName" label="数据模型" width="100"></el-table-column>
        <el-table-column property="priKey" label="字段"></el-table-column>
      </el-table>
    </el-drawer>
  </el-row>
</template>
<style scoped>
#model-graph-container {
  background-image: url('../../../../assets/dataRelationBg.png'); /* 设置背景图像的 URL */
  background-size: cover; /* 控制背景图像的尺寸适应容器 */
  /*background-repeat: repeat;*/
  /* 其他背景样式属性，如背景颜色、重复方式等 */
}
/* 自定义节点的样式 */
.el-tree-node__content:hover {
  background-color: #e0e0e0;
  cursor: pointer;
}

/* 自定义工具提示的样式 */
.el-tooltip__popper {
  z-index: 9999; /* 确保工具提示显示在顶部 */
}

#treeBox {
  margin-top: 1px;

  .el-table thead {
    display: none;
  }
}
.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>
<script>
import { fetchsourceList } from '@/api/metadata/source'
import { deletecolumn, fetchcolumnList, exportcolumn, updatecolumn } from '@/api/metadata/column'
import Import from '@/components/Import/import'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import columnForm from '../../columnForm'
import entityForm from '../../entityForm.vue'
import entityList from '../../entityList.vue'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
import { getModelTree, getFieldRelation, getFieldRelationDetail, getFieldRelationEdgeDetail } from '@/api/metadata/label/metadataLabel'

import customTree from '@/components/customTree/index.vue'
import G6 from '@antv/g6'

export default {
  mounted() {
    // const container = this.$refs.graphContainer;
    // const width = container.offsetWidth;
    // const height = container.offsetHeight;
    //
    // const data = {
    //   nodes: [
    //     { id: 'node0', size: 100 ,label:'数据治理'},
    //     { id: 'node1', size: 70 ,label:'数据治理1'},
    //     { id: 'node2', size: 70 ,label:'数据治理2'},
    //     { id: 'node3', size: 70 ,label:'数据治理3'},
    //     { id: 'node4', size: 40, isLeaf: true },
    //     { id: 'node5', size: 40, isLeaf: true },
    //     { id: 'node6', size: 40, isLeaf: true },
    //     { id: 'node7', size: 40, isLeaf: true },
    //     { id: 'node8', size: 40, isLeaf: true },
    //     { id: 'node9', size: 40, isLeaf: true },
    //     { id: 'node10', size: 40, isLeaf: true },
    //     { id: 'node11', size: 40, isLeaf: true },
    //     { id: 'node12', size: 40, isLeaf: true },
    //     { id: 'node13', size: 40, isLeaf: true },
    //     { id: 'node14', size: 40, isLeaf: true },
    //     { id: 'node15', size: 40, isLeaf: true },
    //     { id: 'node16', size: 40, isLeaf: true },
    //   ],
    //   edges:  [
    //     { source: 'node0', target: 'node1' },
    //     { source: 'node0', target: 'node2' },
    //     { source: 'node0', target: 'node3' },
    //     { source: 'node0', target: 'node4' },
    //     { source: 'node0', target: 'node5' },
    //     { source: 'node1', target: 'node6' },
    //     { source: 'node1', target: 'node7' },
    //     { source: 'node2', target: 'node8' },
    //     { source: 'node2', target: 'node9' },
    //     { source: 'node2', target: 'node10' },
    //     { source: 'node2', target: 'node11' },
    //     { source: 'node2', target: 'node12' },
    //     { source: 'node2', target: 'node13' },
    //     { source: 'node3', target: 'node14' },
    //     { source: 'node3', target: 'node15' },
    //     { source: 'node3', target: 'node16' },],
    // };
    //
    // const graph = new G6.Graph({
    //   container,
    //   width,
    //   height,
    //   layout: {
    //     type: 'force',
    //     preventOverlap: true,
    //     linkDistance: (d) => {
    //       if (d.source.id === 'node0') {
    //         return 100;
    //       }
    //       return 30;
    //     },
    //     nodeStrength: (d) => {
    //       if (d.isLeaf) {
    //         return -50;
    //       }
    //       return -10;
    //     },
    //     edgeStrength: (d) => {
    //       if (d.source.id === 'node1' || d.source.id === 'node2' || d.source.id === 'node3') {
    //         return 0.7;
    //       }
    //       return 0.1;
    //     },
    //   },
    //   // defaultNode: {
    //   //   color: '#5B8FF9',
    //   // },
    //   modes: {
    //     default: ['drag-canvas'],
    //   },
    //
    //   defaultNode: {
    //     size: 60,
    //     color: '#5B8FF9',
    //     // style: {
    //     //   fill: 'lightblue',
    //     //   stroke: 'blue',
    //     // },
    //
    //   },
    //   nodeStateStyles: {
    //     hover: {
    //       fill: 'blue',
    //     },
    //   },
    //
    // });
    // const nodes = data.nodes;
    // graph.data({
    //   nodes,
    //   edges: data.edges.map(function (edge, i) {
    //     edge.id = 'edge' + i;
    //     return Object.assign({}, edge);
    //   }),
    // });
    // graph.render();
    //
    // graph.on('node:dragstart', function (e) {
    //   graph.layout();
    //   refreshDragedNodePosition(e);
    // });
    // graph.on('node:drag', function (e) {
    //   refreshDragedNodePosition(e);
    // });
    // graph.on('node:dragend', function (e) {
    //   e.item.get('model').fx = null;
    //   e.item.get('model').fy = null;
    // });
    // graph.on('node:click', (evt) => {
    //   const node = evt.item; // 获取被点击的节点
    //   console.log('Node clicked:', node.getModel());
    // });
    // if (typeof window !== 'undefined')
    //   window.onresize = () => {
    //     if (!graph || graph.get('destroyed')) return;
    //     if (!container || !container.scrollWidth || !container.scrollHeight) return;
    //     graph.changeSize(container.scrollWidth, container.scrollHeight);
    //   };
    //
    // function refreshDragedNodePosition(e) {
    //   const model = e.item.get('model');
    //   model.fx = e.x;
    //   model.fy = e.y;
    // }
    // graph.data(data);
    // graph.render();
  },
  name: 'columnList',
  components: { columnForm, customTree, Pagination, Import, entityForm, entityList },
  directives: { waves, permission },
  data() {
    return {
      edgesRelation: {},
      openTableTitle: '',
      nodeTableInfo: [],
      edgeInfo: [],
      nodeDrawer: false,
      edgeDrawer: false,
      direction: 'rtl',
      filterText: '',
      tableKey: 0,
      treeList: [],
      labelList: [],
      list: null,
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        columnName: undefined,
        ancestralId: '12',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
      entityQuery: {},
      currentNodekey: '',
      treeData: [],
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      NODE_KEY: 'id',
      nodes: [],
      edges: [],
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },

  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  methods: {
    getId(data) {
      this.listQuery.ancestralId = '5'
      this.listQuery.modelId = data.modelId
      this.getList()
    },
    getTree(data) {
      this.treeList = data
    },
    closeNodeDraw(done) {
      done()
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => {});
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick(data) {
      this.listQuery.modelId = data.id
      this.getList()
    },
    getTreeList() {
      this.listLoading = true
      getModelTree(this.listQuery).then((response) => {
        if (response.data.code === 0) {
          this.treeList = response.data.data
          this.listLoading = false
          // this.$refs.form.setList(this.treeList)
          this.currentNodekey = this.treeList[0].children[0].id
          this.handleNodeClick(this.treeList[0].children[0])
          this.getList()
          this.$nextTick(() => {
            this.$refs.SlotTree.setCurrentKey(this.currentNodekey) //一定要加这个选中了否则样式没有出来
          })
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getLabelList() {
      this.listLoading = true
      fetchMetadataLabelGroupList(this.listQuery).then((response) => {
        if (response.data.code === 0) {
          this.labelList = response.data.data
          this.listLoading = false
          this.$refs.form.setList(this.labelList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    //编辑实体按钮
    handleEdit() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityform.handleUpdate()
        this.$refs.entityform.setList(this.entityQuery)
      } else {
        this.$message.warning('请先选择表')
      }
    },
    //定义实体按钮
    handleCreate() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityform.setList(this.entityQuery)
        this.$refs.entityform.handleCreate()
      } else {
        this.$message.warning('请先选择表')
      }
      // this.$refs.entityform.setList(this.labelList)
    },
    //查看实体按钮
    handleCheck() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityList.setList(this.entityQuery)
        this.$refs.entityList.handleCheck()
      } else {
        this.$message.warning('请先选择表')
      }
    },
    load(tree, treeNode, resolve) {
      resolve(tree.children)
    },
    getListByTreeId(data) {},
    getList() {
      // if(!this.listQuery.sourceId){
      //   this.$message.error("请选择一个数据表")
      //   return;
      // }
      this.listLoading = true
      getFieldRelation({ modelId: '1' }).then((response) => {
        this.list = response.data.data
        let nodeObj
        for (var i = 0; i < this.list.records.length; i++) {
          // { id: 'node15', size: 40, isLeaf: true },
          // { source: 'node0', target: 'node3' },
          nodeObj = {
            id: this.list.records[i].primaryTableid,
            // size: 80,
            label: this.list.records[i].primaryTablename,
            description: this.list.records[i].primaryTablename,
            x: 250,
            y: 150,
          }

          let nodeObj2 = {
            id: this.list.records[i].secondaryTableid,
            // size: 80,
            label: this.list.records[i].secondaryTablename,
            description: this.list.records[i].secondaryTablename,
            x: 250,
            y: 150,
          }
          // alert(this.list.records[i].id)
          let edgeObj = {
            id: this.list.records[i].id,
            source: this.list.records[i].primaryTableid,
            target: this.list.records[i].secondaryTableid,
            label: this.list.records[i].primaryTablename + '-' + this.list.records[i].secondaryTablename,
            relationId: this.list.records[i].id,
          }
          this.nodes.push(nodeObj)
          this.nodes.push(nodeObj2)
          this.edges.push(edgeObj)
        }
        this.nodes = this.nodes.filter((value, index, self) => {
          return self.indexOf(value) === index
        })
        this.setNodes()

        // this.total = response.data.total
        // this.setSort()
        this.listLoading = false
      })
    },
    //获取节点详情
    getRelationDetail(id) {
      this.listLoading = true
      getFieldRelationDetail(id).then((res) => {
        // this.list = response.data.data
        console.log('节点详情数据=' + JSON.stringify(res))
        this.nodeTableInfo = res.data.data.columnModelEntities
        this.openTableTitle = res.data.data.tableName
      })
    },
    //获取连线详情
    getEdgeRelationDetail(id) {
      this.listLoading = true
      getFieldRelationEdgeDetail(id).then((res) => {
        // this.list = response.data.data
        console.log('节点详情数据=' + JSON.stringify(res))
        this.nodeTableInfo = res.data.data.columnModelEntities
        this.openTableTitle = res.data.data.tableName
      })
    },
    handleUpdate(row) {
      this.$refs.form.setList(this.labelList)
      this.$refs.form.handleUpdate(row.id)
    },
    handleUpdate1(row) {
      this.$confirm('确定解除标签绑定吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const data = row
        data.labelId = ''
        updatecolumn(data).then((response) => {
          this.loading = false
          if (response.data.code === 0) {
            this.dialogFormVisible = false
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletecolumn(row.id).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletecolumn(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.downloadLoading = true
      exportcolumn(this.ids).then((response) => {
        this.downloadLoading = true
        if (response.data.code === 0) {
          import('@/vendor/Export2Excel').then((excel) => {
            excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
            this.downloadLoading = false
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    // setSort() {
    //   const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
    //   this.sortable = Sortable.create(el, {
    //     setData: function (dataTransfer) {
    //       // to avoid Firefox bug
    //       // Detail see : https://github.com/RubaXa/Sortable/issues/1012
    //       dataTransfer.setData('Text', '')
    //     },
    //     onEnd: evt => {
    //       const targetRow = this.list.splice(evt.oldIndex, 1)[0]
    //       this.list.splice(evt.newIndex, 0, targetRow)
    //       // TODO：这里完成自己的业务处理
    //     }
    //   })
    // },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    setNodes() {
      // alert("23")
      console.log('===' + JSON.stringify(this.nodes))
      console.log('===2' + JSON.stringify(this.edges))
      const container = this.$refs.graphContainer
      const width = container.offsetWidth
      const height = container.offsetHeight

      const data = {
        nodes: this.nodes,
        //   [
        //   { id: 'node0', size: 100 ,label:'数据治理'},
        //   { id: 'node1', size: 70 ,label:'数据治理1'},
        //   { id: 'node2', size: 70 ,label:'数据治理2'},
        //   { id: 'node3', size: 70 ,label:'数据治理3'},
        //   { id: 'node4', size: 40, isLeaf: true },
        //   { id: 'node5', size: 40, isLeaf: true },
        //   { id: 'node6', size: 40, isLeaf: true },
        //   { id: 'node7', size: 40, isLeaf: true },
        //   { id: 'node8', size: 40, isLeaf: true },
        //   { id: 'node9', size: 40, isLeaf: true },
        //   { id: 'node10', size: 40, isLeaf: true },
        //   { id: 'node11', size: 40, isLeaf: true },
        //   { id: 'node12', size: 40, isLeaf: true },
        //   { id: 'node13', size: 40, isLeaf: true },
        //   { id: 'node14', size: 40, isLeaf: true },
        //   { id: 'node15', size: 40, isLeaf: true },
        //   { id: 'node16', size: 40, isLeaf: true },
        // ],
        edges: this.edges,
        // [
        //     { source: 'node0', target: 'node1' },
        //     { source: 'node0', target: 'node2' },
        //     { source: 'node0', target: 'node3' },
        //     { source: 'node0', target: 'node4' },
        //     { source: 'node0', target: 'node5' },
        //     { source: 'node1', target: 'node6' },
        //     { source: 'node1', target: 'node7' },
        //     { source: 'node2', target: 'node8' },
        //     { source: 'node2', target: 'node9' },
        //     { source: 'node2', target: 'node10' },
        //     { source: 'node2', target: 'node11' },
        //     { source: 'node2', target: 'node12' },
        //     { source: 'node2', target: 'node13' },
        //     { source: 'node3', target: 'node14' },
        //     { source: 'node3', target: 'node15' },
        //     { source: 'node3', target: 'node16' },],
      }

      const graph = new G6.Graph({
        container,
        width,
        height,
        layout: {
          type: 'force',
          nodeStrength: 10, // 节点之间的吸引力，默认值为 100
          edgeStrength: 0.1, // 边之间的斥力，默认值为 0.2
          preventOverlap: true,
          // linkDistance: (d) => {
          //   if (d.source.id === 'node0') {
          //     return 100;
          //   }
          //   return 30;
          // },
          // nodeStrength: (d) => {
          //   if (d.isLeaf) {
          //     return -50;
          //   }
          //   return -10;
          // },
          // edgeStrength: (d) => {
          //   if (d.source.id === 'node1' || d.source.id === 'node2' || d.source.id === 'node3') {
          //     return 0.7;
          //   }
          //   return 0.1;
          // },
        },
        // defaultNode: {
        //   color: '#5B8FF9',
        // },
        modes: {
          // default: ['drag-canvas'],
          default: ['drag-canvas', 'drag-node'],
        },

        defaultNode: {
          type: 'modelRect',
          size: [270, 80],
          // size: 60,
          color: '#5B8FF9',
          style: {
            radius: 5,
            stroke: '#69c0ff',
            fill: '#ffffff',
            lineWidth: 1,
            fillOpacity: 1,
          },
          labelCfg: {
            style: {
              fill: '#595959',
              fontSize: 14,
            },
            offset: 30,
          },
          preRect: {
            show: true,
            width: 4,
            fill: '#40a9ff',
            radius: 2,
          },
          // configurations for the four linkpoints
          linkPoints: {
            top: false,
            right: false,
            bottom: false,
            left: false,
            // the size of the linkpoints' circle
            size: 10,
            lineWidth: 1,
            fill: '#72CC4A',
            stroke: '#72CC4A',
          },
          // configurations for the icon
          logoIcon: {
            // whether to show the icon
            show: true,
            x: 0,
            y: 0,
            // the image url for the icon, string type
            img: 'https://gw.alipayobjects.com/zos/basement_prod/4f81893c-1806-4de4-aff3-9a6b266bc8a2.svg',
            width: 16,
            height: 16,
            // adjust the offset along x-axis for the icon
            offset: 0,
          },
          // configurations for state icon
          stateIcon: {
            // whether to show the icon
            show: true,
            x: 0,
            y: 0,
            // the image url for the icon, string type
            img: 'https://gw.alipayobjects.com/zos/basement_prod/300a2523-67e0-4cbf-9d4a-67c077b40395.svg',
            width: 16,
            height: 16,
            // adjust hte offset along x-axis for the icon
            offset: -5,
          },
          // style: {
          //   fill: 'lightblue',
          //   stroke: 'blue',
          // },
        },
        nodeStateStyles: {
          hover: {
            fill: 'blue',
          },
        },
      })
      const nodes = data.nodes
      graph.data({
        nodes,
        edges: data.edges.map(function (edge, i) {
          edge.id = 'edge' + i
          return Object.assign({}, edge)
        }),
      })
      graph.render()
      graph.on('node:dragstart', function (e) {
        graph.layout()
        refreshDragedNodePosition(e)
      })
      graph.on('node:drag', function (e) {
        refreshDragedNodePosition(e)
      })
      graph.on('node:dragend', function (e) {
        e.item.get('model').fx = null
        e.item.get('model').fy = null
      })
      graph.on('node:click', (evt) => {
        const node = evt.item // 获取被点击的节点
        console.log('Node clicked:', node.getModel())
        this.getRelationDetail(node.getModel().id)
        this.nodeDrawer = true
      })
      graph.on('edge:click', (evt) => {
        const edge = evt.item // 获取被点击的边
        console.log('Edge clicked1:===' + JSON.stringify(edge.getModel()))
        console.log('Edge clicked2:===', edge.getModel().relationId)
        this.list
        this.edgesRelation = this.list.records.filter((item) => item.id === edge.getModel().relationId)
        console.log(JSON.stringify(this.edgesRelation))
        var priObj = {
          relationType: '主表',
          tableName: this.edgesRelation[0].primaryTablename,
          priKey: this.edgesRelation[0].primaryFieldname,
        }
        var sceObj = {
          relationType: '次表',
          tableName: this.edgesRelation[0].secondaryTablename,
          priKey: this.edgesRelation[0].secondaryFieldname,
        }
        this.edgeInfo = []
        this.edgeInfo.push(priObj)
        this.edgeInfo.push(sceObj)
        this.edgeDrawer = true
        // this.getEdgeRelationDetail(edge.getModel().relationId)
        // 执行你的自定义操作，例如弹出信息框或导航到相关页面
      })
      if (typeof window !== 'undefined')
        window.onresize = () => {
          if (!graph || graph.get('destroyed')) return
          if (!container || !container.scrollWidth || !container.scrollHeight) return
          graph.changeSize(container.scrollWidth, container.scrollHeight)
        }

      function refreshDragedNodePosition(e) {
        const model = e.item.get('model')
        model.fx = e.x
        model.fy = e.y
      }
      graph.data(data)
      graph.render()
    },
  },
}
</script>
<style lang="scss" scoped></style>
